<?php
session_start();

if ( $_SESSION['manager'] && $_SESSION['manager']['is_admin'] )
{
    require_once('../inc/config.db.php');
    switch( $_POST['action'] )
    {
	case	'add':
	    mysql_query
	    (
		sprintf
		(
		    'INSERT INTO `manager` (`login`,`manager_name`,`password`,`is_admin`)'
			.' VALUES (\'%s\',\'%s\',\'%s\',\'%s\')',
		    mysql_escape_string($_POST['login']),
		    mysql_escape_string($_POST['manager_name']),
		    mysql_escape_string($_POST['password']),
		    mysql_escape_string($_POST['is_admin'])
		)
	    );

	    if ( mysql_affected_rows()==1 )
	    {
		print json_encode(array('code'=>200));
	    }
	    else
	    {
		print json_encode(array('code'=>500,text=>mysql_error()));
	    }
	    break;

	case	'update':
	    if ( isset($_POST['id']) )
	    {
		if ( $_POST['id'] = preg_replace('/^manager_(\d+)$/','$1',$_POST['id']) )
		{
		    mysql_query(sprintf('UPDATE `manager` SET `is_admin`=%d WHERE `id`=%d',$_POST['is_admin'],$_POST['id']));
		    if ( mysql_affected_rows()==1 )
		    {
			print json_encode(array('code'=>200));
		    }
		    else
		    {
			print json_encode(array('code'=>500,'text'=>mysql_error()));
		    }
		}
		else
		{
		    print json_encode(array('code'=>500,'text'=>'parser error'));
		}
	    }
	    else
	    {
		print json_encode(array('code'=>500,'text'=>'no id presented'));
	    }
	    break;

	case	'delete':
	    if ( isset($_POST['id']) )
	    {
		if ( $_POST['id'] = preg_replace('/^manager_(\d+)$/','$1',$_POST['id']) )
		{
		    mysql_query('SELECT `id` FROM `customer` WHERE `manager_id`='.$_POST['id']);

		    if ( (mysql_affected_rows()>0) && isset($_POST['new_id']) )
		    {
			mysql_query(sprintf('UPDATE `customer` SET `manager_id`=%d WHERE `manager_id`=%d',$_POST['new_id'],$_POST['id']));
			mysql_query('DELETE FROM `manager` WHERE `id`='.$_POST['id']);
			if ( mysql_affected_rows()==1 )
			{
			    print json_encode(array('code'=>200));
			}
			else
			{
			    print json_encode(array('code'=>500,'text'=>mysql_error()));
			}
		    }
		    else
		    if ( (mysql_affected_rows()>0) && !isset($_POST['new_id']) )
		    {
			print json_encode(array('code'=>400));
		    }
		    else
		    if ( mysql_affected_rows()==0 )
		    {
			mysql_query('DELETE FROM `manager` WHERE `id`='.$_POST['id']);
			if ( mysql_affected_rows()==1 ) { print json_encode(array('code'=>200)); }
			else { print json_encode(array('code'=>500,'text'=>mysql_error())); }
		    }
		    else
		    {
			print json_encode(array('code'=>500,'text'=>'Unhandled error: '.mysql_error()));
		    }
		}
		else
		{
		    print json_encode(array('code'=>500,'text'=>'parser error'));
		}
	    }
	    break;
    }
}
?>
